package com.punai.common.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.punai.common.core.domain.entity.SysPnDictionary;
import com.punai.common.core.redis.PnDictCache;
import com.punai.common.core.text.Convert;
import com.punai.common.utils.spring.SpringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class PnDictUtil {

    // 字典緩存
    private static final PnDictCache pnDictCache = SpringUtils.getBean(PnDictCache.class);
    // 最小的代碼
    private static final String minCode = "001";
    // 最大的代碼
    private static final String maxCode = "999";

    private static final int FIRST_TIER = 0;

    public static SysPnDictionary getDictionary(String code) {
        return pnDictCache.getFromCache(code);
    }

    public static Collection<SysPnDictionary> getDictionarys(String pcode) {
        Collection<String> dics = pnDictCache.getMutilDic(pcode + minCode, pcode + maxCode);
        final List<SysPnDictionary> dictionarys = new ArrayList<SysPnDictionary>();
        dics.forEach(dic -> {
            SysPnDictionary dictionary = JSONUtil.toBean(Convert.toStr(dic), SysPnDictionary.class);
            dictionarys.add(dictionary);
        });

        dictionarys.sort( (pre, next) -> {
            Long preSort = pre.getSorting() == null ? 0L: pre.getSorting();
            Long nexteSort = next.getSorting() == null ? 0L: next.getSorting();

            return preSort.compareTo(nexteSort);
        });
        return dictionarys;
    }


    /**
     *
     * 说明：取得父节点的所有的子菜单
     * @Title: getDictionarys
     * @author fuyp
     * @param pcode 父节点代码
     * @return Collection<Dictionary>
     * @date: Jul 16, 2017 12:43:31 PM
     */
    public static Collection<SysPnDictionary> getDictionarysWithChild(String pcode) {
        Collection<String> dics = pnDictCache.getMutilDic(pcode + minCode, pcode + maxCode);
        if (CollectionUtil.isEmpty(dics)) {
            return null;
        }
        final List<SysPnDictionary> dictionarys = new ArrayList<SysPnDictionary>();
        dics.forEach(dic -> {
            SysPnDictionary dictionary = JSONUtil.toBean(Convert.toStr(dic), SysPnDictionary.class);
            Collection<SysPnDictionary> childs = getDictionarysWithChild(dictionary.getCode());
            if (CollectionUtil.isNotEmpty(childs)) {
                dictionary.setChildren(childs);
            }
            dictionarys.add(dictionary);
        });

        dictionarys.sort( (pre, next) -> {
            Long preSort = pre.getSorting() == null ? 0L: pre.getSorting();
            Long nexteSort = next.getSorting() == null ? 0L: next.getSorting();
            return preSort.compareTo(nexteSort);
        });
        return dictionarys;
    }

}
